﻿using EFCORE仓储模式.Contracts;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace EFCORE仓储模式.Data.Repositories
{
    public abstract class RepositoryBase<T> : IRepositoryBase<T> where T : class
    {
        protected DataMangermentDbContext _DbContext { get; set; }

        protected RepositoryBase(DataMangermentDbContext dbContext)
        {
            _DbContext = dbContext;
        }

        public void Create(T entity)
        {
            _DbContext.Set<T>().Add(entity);
        }

        public void Delete(T entity)
        {
            _DbContext.Set<T>().Remove(entity);
        }

        public IQueryable<T> FindAllWithNoTracking()
        {
            //AsNoTracking表示只查询结果，不跟踪实体
            return _DbContext.Set<T>().AsNoTracking();
        }

        public IQueryable<T> FindAll()
        {
            return _DbContext.Set<T>().AsQueryable();
        }


        public IQueryable<T> FindByCondition(Expression<Func<T, bool>> expression)
        {
            return _DbContext.Set<T>().Where(expression).AsNoTracking();
        }

        public void Update(T entity)
        {
            _DbContext.Set<T>().Update(entity);
        }
    }
}